package rmi.server;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;

import model.PersistentInterface;

import toolkit.Debug;

public class Remote
{
	@PersistenceContext
	protected EntityManager entityManager;
	
	public void setEntityManager(EntityManager entityManager)
	{
		this.entityManager = entityManager;
	}
	
	public void storeEntity(PersistentInterface entity)
	{
		if (entity.check())
		{
			EntityTransaction entityTransaction = entityManager.getTransaction();
			
			entityTransaction.begin();
			
			try
			{
				if (entity.getId() == 0) 
				{ 
					entityManager.persist(entity); // INSERT INTO
				} 
				else 
				{ 
					entityManager.merge(entity); // UPDATE
				}
				
				entityTransaction.commit();
			}
			catch (Exception e)
			{
				Debug.log(e);
				
				entityTransaction.rollback();
			}
		}
	}
	
	public void removeEntity(PersistentInterface entity)
	{
		EntityTransaction entityTransaction = entityManager.getTransaction();
		
		entityTransaction.begin();
		
		try
		{
			entity = entityManager.find(entity.getClass(), entity.getId());
			
			entityManager.remove(entity);
			
			entityTransaction.commit();
		}
		catch (Exception e)
		{
			Debug.log(e);
			
			entityTransaction.rollback();
		}
	}
}
